package dexter.core.front;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Properties;

import dexter.net.Consumer;
import dexter.net.msg.common.RequestListener;
import dexter.testing.EvaluationValues;
import dexter.util.IdGenerator;
import dexter.util.PropertiesReader;

public class FrontEnd {

	private Properties props;
	private Consumer consumer;
	private Hashtable<String, String> jobs;
	
	private static String status;

	public FrontEnd(Properties props) {
		this.props = props;
		int port = Integer.parseInt(props.getProperty("front_port"));
		consumer = new Consumer(port);
		jobs = new Hashtable<String, String>();
		
	}
	
	public static boolean check(String groupId) {
		return DatabaseManager.checkGroupById(groupId);
	}
	
	public static String saveExp(String groupId, String path, boolean remoteMode, EvaluationValues eval) {
	
		return DatabaseManager.persistExperiment(groupId, path, remoteMode, 
				eval.getResultValue(0), eval.getResultInfo(0), 
				eval.getResultValue(1), eval.getResultInfo(1), 
				eval.getResultValue(2), eval.getResultInfo(2));
	}
	
	public static void saveJob(String jobId, String groupId, String publicIp) {
		
		DatabaseManager.persistJob(jobId, groupId, publicIp);
	}
	
	public String generateJob(String groupId) {
		
		String jobId = IdGenerator.generate();
		while (jobs.containsKey(jobId)) jobId = IdGenerator.generate();
		
		jobs.put(jobId, groupId);
		return jobId;
	}
	
	public String finishJob(String jobId) {
		String groupId = jobs.remove(jobId);
	    return groupId;
    }
	
	public static String getStatus() {		
		return status;
	}
	
	public static void setStatus(String s) {
	    status = s;	
	}
	
	public Properties getConfig() {
		return props;
	}

	public void start(){
		  
		  RequestListener clistener = new FrontListener(this);
		  try {
			consumer.receive(clistener);
			System.out.println("FrontEnd: Waiting for test requests");
		} catch (IOException e) {
			e.printStackTrace();
		}
		 
	}
	
	public static void main(String[] args) {
		
		System.out.println("FRONT INIT");
		
		//Read main parameters
		String config="config.properties";
		
		for(int i=0; i<args.length; i+=2){
			if(args[i].equals("-p")){
				config=args[i+1];
			}		
		}	
		System.out.println(config);
		Properties props=PropertiesReader.getProperties(config);
		
		//int PORT = 54323;
		//if (args.length>0) PORT = Integer.parseInt(args[0]); 
	 
		
		FrontEnd front = new FrontEnd(props);
		
		//int PORT = Integer.parseInt(props.getProperty("front_port"));
		//System.out.println("FrontEnd: Opening port "+PORT);
		front.start();
		
		//Monitor monitor = new Monitor();
		
		System.out.println("FRONT END");
		
	}




}
